//
//  HMNetworkTools.swift
//  swift下的网络框架封装
//
//  Created by 周英培 on 16/5/22.
//  Copyright © 2016年 周英培. All rights reserved.
//

import UIKit

//导入第三方框架
import AFNetworking

//声明枚举
//可以枚举任何类型
enum HTTPMethods : Int {

    case GET
    case POST

}

struct API {
    //基URL
    static let hostName = "https://api.weibo.com/"
    
    //请求token
    static let loadToken = "oauth2/access_token"
    
    //请求用户信息
    static let loadUserInfo = "2/users/show.json"
    
    //首页信息
    static let loadHomeInfo = "2/statuses/home_timeline.json"
    
    //发布微博
    static let sendStatus = "2/statuses/update.json"
    
    //发布图片微博
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
}

class HMNetworkTools: AFHTTPSessionManager {

    //声明单例对象
    static let sharedTools : HMNetworkTools = {
    
        //baseURL: 把URL前面一样的部分 声明为基础的URL地址
        let url = NSURL(string: API.hostName)
        let tools = HMNetworkTools(baseURL: url)
        
        //设置支持的格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    
    }()
    
    //MARK:封装GET 和 POST方法
    /*
     tools .GET(<#T##URLString: String##String#>, parameters: <#T##AnyObject?#>, success: ((NSURLSessionDataTask, AnyObject?) -> Void)?, failure: <#T##((NSURLSessionDataTask?, NSError) -> Void)?##((NSURLSessionDataTask?, NSError) -> Void)?##(NSURLSessionDataTask?, NSError) -> Void#>)
     */
    func request(method:HTTPMethods,urlString:String,parameters :AnyObject?,finished:(responseObject : AnyObject?,error : NSError?)->()) {
    
//        if method == .GET {
//            
//            //"_"表示忽略的意思 意思是那个没有用上，所以可以忽略
//            
//            GET(urlString, parameters: nil, success: { (_, result) in
//                
//                
//                //执行成功的回调
//                finished(responseObject: result, error: nil)
//                
//                }, failure: { (_, error) in
//                    
//                    //执行失败的回调
//                    finished(responseObject: nil, error: error)
//            })
//        } else {
//        
//            POST(urlString, parameters: nil, success: { (_, result) in
//                
//                //执行成功的回调
//                finished(responseObject: result, error: nil)
//                
//                }, failure: { (_, error) in
//                    
//                    //执行失败的回调
//                    finished(responseObject: nil, error: error)
//                    
//            })
//        
//        }
        
        //封装闭包参数，将相同的闭包当做参数传递
        let success = {(task:NSURLSessionDataTask,result:AnyObject?)->()in
        
        finished(responseObject: result, error: nil)
            
        }
        
        let failure = {(task:NSURLSessionDataTask?,error:NSError) -> () in
        
        finished(responseObject: nil, error: error)
        
        }
        
        if method == .GET {
            
//            GET(urlString, parameters: parameters, success: success, failure: failure)
              GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        } else {
        
//            POST(urlString, parameters: parameters, success: success, failure: failure)
              POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    
    }
    
}

//MARK:将请求的token值和用户信息的方法封装在这个网络请求类里面
extension HMNetworkTools {

    //获取token值
    func loadToken(code:String,finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
    
//        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        //调用封装的方法
        request(.POST, urlString: API.loadToken, parameters: parameters, finished: finished)
    
    }
    
    //获取用户信息
    func loadUserInfo(response:[String : AnyObject],finished: (responseObject: AnyObject?, error: NSError?) -> ()){

//        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //字典里面不能为nil
        
        let access_token = response["access_token"]!
        
        let uid = response["uid"]!
        
        let parameters = ["access_token":access_token,"uid":uid]

        request(.GET, urlString: API.loadUserInfo, parameters: parameters, finished: finished)

}
    
}

//获取首页信息
extension HMNetworkTools {

    func loadHomeData(since_id : Int64,max_id: Int64,finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
    
        guard let token = HMUserInfoViewModel.sharedUserInfoViewModel.userInfoModel?.access_token else {
        
        return
        
        }
        
        //要添加参数 所以是可变的
        var parameters = ["access_token":token]
        
        //since_id,若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        if since_id > 0 {
            //将此参数添加参数字典里面
            parameters["since_id"] = "\(since_id)"
        }
        
        //max_id若指定此参数，则返回ID小于或等于max_id的微博，默认为0
        //会有bug 会返回max_id 对应的微博  解决此问题 max_id - 1
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        request(.GET, urlString: API.loadHomeInfo, parameters: parameters, finished: finished)
        
    
    
    }

}

extension HMNetworkTools {

    //发布微博 或者发布图片微博
    func sendStatus(status:String,images:[UIImage],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        
        guard let token = HMUserInfoViewModel.sharedUserInfoViewModel.userInfoModel?.access_token else {
            
            return
            
        }
    
        let parameters = ["access_token":token,"status":status]
        
        //判断有图片时 发布图片微博 请求必须用POST方式提交，并且注意采用multipart/form-data编码方式；
        if images.count > 0 {
            
//            let imageData = UIImagePNGRepresentation(images.first!)!
            // 图片上传  AFN已经封装好AFN上传方法 使用POST方法  系统的上传图片的post方法
            /*
             1.data          需要上传的二进制数据
             2.name          服务器接收的字段
             3.fileName      服务器存储的上传文件的名称  但是这个地方可以随便去  新浪微博服务器会自己根据自己的规则命名
             4.mimeType      上传的文件的类型  application/octet-stream 忽略文件类型
             */
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                
                //将上传的二进制数据拼接到formdata上面
                //实现多图上传的方法：将多图上传的二进制数据拼接到formdata上面 let imageData = UIImagePNGRepresentation(images.first!)! 并且放在循环里面
                for image in images {
                
                    let imageData = UIImagePNGRepresentation(image)!
                
                    formdata.appendPartWithFileData(imageData, name: "pic", fileName: "jaychou", mimeType: "application/octet-stream")
                }
                
                }, progress: nil, success: { (_, result) in
                    
                    finished(responseObject: result, error: nil)
                    
                }, failure: { (_, error) in
                    
                    finished(responseObject: nil, error: error)
            })
            
        } else {//没有图片时 发布文案微博
        
            request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        
        }
        
    
    }

}
